package com.kayak.easysp.busi.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.rpc.RpcException;
import com.kayak.Global;
import com.kayak.dubbo.bean.ConsumerBean;
import com.kayak.dubbo.bean.RpcBean;
import com.kayak.easysp.transbase.TransBean;
import com.kayak.easysp.util.ConsumerBeanUtil;
import com.kayak.easysp.util.ErrorCodeEasysp;
import com.kayak.easysp.util.TransUtilEasysp;
import com.kayak.exception.ErrorException;
import com.kayak.kkutils.JsonUtil;
import com.kayak.kkweb.sys.RequestSupport;
import com.kayak.kkweb.sys.SysBeans;
import com.kayak.service.enterprise.salaryPay.CreateSpBankFileInterface;
/**
 * 生成发放表（下载）
 * @author myt
 *
 */
@WebServlet(urlPatterns = "/salarydownload")
public class CreateSalaryDownloadAction extends HttpServlet{
	 
//	private static final long serialVersionUID = 1L;
	public final static Logger log = LoggerFactory.getLogger(CreateSalaryDownloadAction.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
	    TransBean transBean = new TransBean();
		Map<String, Object> params = RequestSupport.getParameters();
	    transBean.getLocalMap().putAll(params);
		//获取request中的数据
		ConsumerBean consumerBean=ConsumerBeanUtil.getConsumerBean(transBean);
		consumerBean.addRequest("head_jessionid", transBean.getLocal("head_jessionid"));
		consumerBean.addRequest("ent_id", transBean.getLocal("ent_id"));
		consumerBean.addRequest("group_id", transBean.getLocal("group_id"));
		consumerBean.addRequest("plan_id", transBean.getLocal("plan_id"));
		consumerBean.addRequest("banks", transBean.getLocal("banks"));
		RpcBean rpcBean=null;
		CreateSpBankFileInterface createSpBankFileService = (CreateSpBankFileInterface) SysBeans.getBean("createSpBankFileService");
		try {
			rpcBean=createSpBankFileService.execute(consumerBean);
			TransUtilEasysp.verifyServiceReturn(rpcBean);
		} catch (RpcException | ErrorException e) {
			e.printStackTrace();
			transBean.addResponse("ret_code", ErrorCodeEasysp.ERROR_EASYSP_F990_CODE);
			transBean.addResponse("ret_msg", ErrorCodeEasysp.ERROR_EASYSP_F990_MSG);		
			returnClient((ServletResponse) response, transBean);
			return;
		}
		String zipfile = rpcBean.getResponse("zipfile");
		String zipFileName = rpcBean.getResponse("zipFileName");
		String suffix = rpcBean.getResponse("suffix");
		
		if("".equals(zipfile)||zipfile==null){
			transBean.addResponse("ret_code", ErrorCodeEasysp.ERROR_EASYSP_SYSTEMBUSY_CODE);
			transBean.addResponse("ret_msg", ErrorCodeEasysp.ERROR_EASYSP_SYSTEMBUSY_MSG);		
			returnClient((ServletResponse) response, transBean);
			return;
		}
		
		//得到要下载的文件
		File file = new File(zipfile);
		//如果文件不存在
		if(!file.exists()){
			transBean.addResponse("ret_code", ErrorCodeEasysp.ERROR_EASYSP_SYSTEMBUSY_CODE);
			transBean.addResponse("ret_msg", ErrorCodeEasysp.ERROR_EASYSP_SYSTEMBUSY_MSG);		
			returnClient((ServletResponse) response, transBean);
			return;
		}
		//设置响应头，控制浏览器下载该文件
		response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
		//读取要下载的文件，保存到文件输入流
		FileInputStream in = new FileInputStream(zipfile);
		//创建输出流
		OutputStream out = response.getOutputStream();
		//创建缓冲区
		byte buffer[] = new byte[1024];
		int len = 0;
		//循环将输入流中的内容读取到缓冲区当中
		while((len=in.read(buffer))>0){
		//输出缓冲区的内容到浏览器，实现文件下载
		out.write(buffer, 0, len);
		}
		//关闭文件输入流
		in.close();
		//关闭输出流
		out.close();
		TransUtilEasysp.deleteFileOrDirectory(zipfile);
		transBean.addResponse("ret_code","0000");
		transBean.addResponse("ret_msg", "下载成功");		
		returnClient((ServletResponse) response, transBean);
		return;	
	}
	
	private static void returnClient(ServletResponse httpResponse, TransBean transBean) {
		//判断transBrean.response是否为空
		if(null==transBean.getResponse()||null==transBean.getResponse().get("ret_code")||transBean.getResponse().get("ret_code").equals("")){
			transBean.addResponse("ret_code", transBean.getLocalParam("ret_code"));
			transBean.addResponse("ret_msg", transBean.getLocalParam("ret_msg"));
		}

		String retData = JsonUtil.objectToJsonNull(transBean.getResponse());
		log.info("retrunClient:[{}]", retData);
		//返回执行结果到前端
		OutputStream out = null;
		try {
			out = httpResponse.getOutputStream();
			out.write(retData.getBytes(Global.charset()));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Map<String, Object> params = RequestSupport.getParameters();
		params.put("ip", request.getRemoteAddr());//获取请求ip
		System.out.println(params.get("email"));
		System.out.println(params.get("group_id"));
		//TransBase.doService(transCode, params, response);
		
		this.doGet(request, response);
	}
}
